<template>
  <div class="menuManage">
    <g-mobile ref="mobile" :inputname="menuForm.name" :nameshow="nameShow" @selectMenu="handleSelectMenu" v-loading="loadMenu"></g-mobile>
    <div class="editBox">
      <div class="hd" v-show="nameShow">
        <span>{{menuForm.name}}</span>
        <a class="delete" @click="handleDelMenu">删除菜单</a>
      </div>
      <div class="info">{{info}}</div>
      <el-form :model="menuForm" ref="menuForm" v-show="nameShow">
        <el-form-item label="菜单名称" label-width="90px">
          <el-input v-model="menuForm.name" :maxlength="16"></el-input>
          <div>字数不超过{{maxName}}个汉字或{{maxName*2}}个字母</div>
        </el-form-item>
        <el-form-item v-if="ifShowContent" label="菜单内容" label-width="90px">
          <el-radio-group v-model="menuForm.type">
            <el-radio label="media_id">发送消息</el-radio>
            <el-radio label="view">跳转网页</el-radio>
          </el-radio-group>        
        </el-form-item>
        <editor-lite 
          ref="editor" 
          v-if="ifShowContent" 
          v-show="menuForm.type==='media_id'" 
          :editorData="editorData" 
          :showText="false"
          @change="handleEditorChange"></editor-lite>
        <div v-show="menuForm.type==='view'" class="link-box">
          <p class="tips">订阅者点击该子菜单会跳到以下链接</p>
          <el-form-item label="页面地址" label-width="80px">
            <el-input v-model="viewUrl"></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-button type="primary" @click="handleSaveMenu('menuForm')" :loading="isSave">保存</el-button>
  </div>
</template>
<script>
  import {mapActions, mapState, mapMutations} from 'vuex'
  import gMobile from '@/components/common/content/mobile'
  import editorLite from '@/components/common/content/wechatEditorLite2'
  export default {
    components: {gMobile, editorLite},
    data () {
      return {
        menuForm: {
          name: '',
          type: '',
          key: null
        },
        viewUrl: '',
        info: '',
        editorData: {},
        menuType: null,
        isSave: false,
        loadMenu: true,
        nameShow: false
      }
    },
    mounted () {
      this.initPageData()
    },
    watch: {
      curMenu: {
        deep: true,
        handler: function (obj) {
          this.menuForm = obj
          if (obj.type === 'view') {
            if (obj.media_id) {
              this.viewUrl = ''
            } else if (obj.url) {
              this.viewUrl = obj.url
            } else if (!this.url) {
              obj.url = this.viewUrl
            }
          }
        }
      },
      menuForm: {
        deep: true,
        handler: function (val) {
          this.UPDATE_CUR_MENU(val)
        }
      },
      viewUrl (val) {
        this.UPDATE_CUR_MENU({url: val})
      },
      sourceInfo: {
        deep: true,
        handler: function (obj) {
          obj && this.UPDATE_CUR_MENU({url: obj.url, media_id: obj.mediaid})
        }
      }
    },
    computed: {
      ...mapState({
        curMenu: state => state.wechatManage.curMenu,
        wechatMenu: state => state.wechatManage.wechatMenu,
        subMenuIndex: state => state.wechatManage.subMenuIndex,
        sourceInfo: state => state.sourceManage.sourceInfo
      }),
      curMenu: {
        get () {
          return this.$store.state.wechatManage.curMenu
        },
        set (val) {
          this.SET_CUR_MENU(val)
        }
      },
      maxName () {
        if (this.menuType === 'sup') {
          return 4
        } else {
          return 8
        }
      },
      // 是否显示内容模块
      ifShowContent () {
        return this.curMenu.sub_button && this.curMenu.sub_button.length === 0
      }
    },
    methods: {
      ...mapActions(['getWechatMenu', 'saveWechatMenu', 'getSourceMoreInfo', 'getWxNewsByMediaid', 'getWxMenuSource']),
      ...mapMutations(['SET_WECHAT_MENU', 'UPDATE_CUR_MENU', 'SET_CUR_MENU']),
      // 页面初始化
      async initPageData () {
        this.appid = this.$route.params.appid
        const res = await this.getWechatMenu(this.appid)
        if (res.data.code === 1) {
          this.loadMenu = false
        }
      },
      // 选择菜单
      async handleSelectMenu (text) {
        this.viewUrl = ''
        if (!this.nameShow) {
          this.nameShow = true
        }
        this.$refs.editor && this.$refs.editor.clear()
        const menu = this.curMenu
        this.menuType = this.$refs.mobile.showSubMenu === null ? 'sup' : 'sub'
        if (menu.sub_button.length === 5) {
          this.info = '已为“菜单名1”添加了5个子菜单，无法设置其他内容。'
        } else if (menu.sub_button.length) {
          this.info = '已添加子菜单，仅可设置菜单名称。'
        } else {
          this.info = ''
        }
        if (menu.media_id) {
          const mediaid = menu.media_id // todo: menu.media_id莫名消失
          const res = await this.getWxMenuSource({appid: this.appid, mediaid: menu.media_id})
          if (res.data.data.type !== 'news') {
            this.editorData = res.data.data.info
          } else {
            this.editorData = {newsList: res.data.data.info, msgType: 'news', mediaid: mediaid}
          }
        }
      },
      handleEditorChange () {
        const editor = this.$refs.editor
        this.curMenu = {...this.curMenu, msgType: editor.getContent.msgType, media_id: editor.getContent.mediaid}
      },
      // 保存菜单
      handleSaveMenu (form) {
        if (!this.checkData()) return
        this.isSave = true
        this.saveWechatMenu({
          appid: this.appid,
          menus: {menu: {button: this.wechatMenu}}
        }).then((res) => {
          this.isSave = false
          this.$message.success(res.data.msgZ)
          if (res.data.code === 1) {
            this.menuForm.name = ''
            this.nameShow = false
            this.$store.state.wechatManage.curMenu = {
              key: '',
              media_id: '',
              name: '',
              sub_button: [],
              type: '',
              url: null
            }
            // this.$store.state.wechatManage.menuIndex = null
            // this.$store.state.wechatManage.subMenuIndex = null
            this.initPageData()
          }
        })
      },
      // 删除菜单
      handleDelMenu () {
        const index = this.$refs.mobile.showMenu
        const subIndex = this.$refs.mobile.showSubMenu
        if (this.wechatMenu[index].sub_button.length > 0 && subIndex === null) {
          this.$message.warning('该菜单包含有子菜单，不能直接删除，请先删除子菜单')
          return false
        }
        // this.nameShow = false
        if (subIndex !== null) { // 删除子菜单
          this.wechatMenu[index].sub_button.splice(subIndex, 1)
          if (this.wechatMenu[index].sub_button.length === 0) {
            this.wechatMenu[index].key = '4'
            this.wechatMenu[index].type = 'media_id'
            this.wechatMenu[index].media_id = undefined
            this.wechatMenu[index].url = undefined
            this.$refs.mobile.handleMenuClick(index, this.wechatMenu[index])
          } else {
            let nextSubIndex = subIndex === 0 ? 0 : (subIndex - 1)
            this.$refs.mobile.handleSubMenuClick(nextSubIndex, this.wechatMenu[index].sub_button[nextSubIndex])
          }
          this.SET_WECHAT_MENU(this.$_.cloneDeep(this.wechatMenu))
        } else {  // 删除主菜单
          this.wechatMenu.splice(index, 1)
          this.SET_WECHAT_MENU(this.wechatMenu)
          let nextIndex = index === 0 ? 0 : (index - 1)
          this.$refs.mobile.handleMenuClick(nextIndex, this.wechatMenu[nextIndex])
        }
      },
      // 切换菜单内容
      changeMenuCont () {
        console.log(this.curMenu)
      },
      // 保存校验
      checkData () {
        for (let i = 0; i < this.wechatMenu.length; i++) {
          let item = this.wechatMenu[i]
          if (!this.checkName(item.name, 8, '主')) {
            return false
          }
          if (item.sub_button.length === 0) {
            if (!this.checkDetail(item, '主')) {
              return false
            }
          }
          for (let j = 0; j < item.sub_button.length; j++) {
            let subItem = item.sub_button[j]
            if (!this.checkName(subItem.name, 16, '子')) {
              return false
            }
            if (!this.checkDetail(subItem, '子')) {
              return false
            }
          }
        }
        return true
      },
      // 检测内容详细
      checkDetail (obj, belong) {
        let urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/
        if (obj.type === 'view') {
          if (obj.url === '') {
            this.$message.warning(belong + '菜单页面地址不能为空')
            return false
          }
          if (!urlReg.test(obj.url)) {
            this.$message.warning(belong + '菜单页面地址格式不正确')
            return false
          }
        } else {
          if (!obj.media_id) {
            this.$message.warning(belong + '菜单发送消息内容不能为空')
            return false
          }
        }
        return true
      },
      // 检测菜单名
      checkName (value, len, belong) {
        if (!value) {
          this.$message.warning(belong + '菜单名称不能为空')
          return false
        } else if (this.getByteLen(value) > len) {
          this.$message.warning(belong + '菜单字符长度不能超过' + len + '位')
          return false
        }
        return true
      },
      // 计算中英文字符长度
      getByteLen (val) {
        var len = 0
        for (var i = 0; i < val.length; i++) {
          var a = val.charAt(i)
          if (a.match(/[^\x00-\xff]/ig)) {
            len += 2
          } else {
            len += 1
          }
        }
        return len
      }
    }
  }
</script>
<style lang="scss">
  .menuManage{
    width:950px;text-align:center;
    .g-mobile{float:left;}
    .editBox{
      margin-left:345px;padding: 0 20px 20px 20px;width:560px;height:560px;background:#f4f5f9;border:1px solid #e7e7eb;overflow:hidden;text-align:left;
      .hd{margin-bottom:10px;padding:10px 0;line-height:20px;font-size:14px;border-bottom: 1px solid #e7e7eb;overflow:hidden;}
      .info{height:14px;line-height:14px;margin-bottom:10px;font-size:14px;}
      .delete{float:right;color:#459ae9;cursor:pointer;}
    }
    .link-box{
      &{padding:16px 20px;border:1px solid #e7e7eb;background:#fff;}
      .tips{font-size:14px;margin-bottom:10px;}
    }
    .el-button{margin-top:20px;}
  }
</style>
